import React, { useContext, useReducer, useState } from 'react';

const C = React.createContext<any>(null);

function Baba() {
  const { n, setN } = useContext(C);
  const add = () => {
    setN((n) => n + 1);
  };
  return (
    <div>
      这是爸爸{n}
      <button onClick={add}>+1</button>
      <Child></Child>
    </div>
  );
}

function Child() {
  const { n, setN } = useContext(C);
  const add = () => {
    setN((n) => n + 1);
  };
  return (
    <div>
      这是儿子{n}
      <button onClick={add}>+1</button>
    </div>
  );
}

 function App() {
  const [n, setN] = useState(0);
  return (
    <C.Provider value={{ n, setN }}>
      这是爷爷
      <Baba></Baba>
    </C.Provider>
  );
}

const reducer = (state, action) => {
  if (action.type === 'add') return state + 1;
  else return state;
};

export default function Counter() {
  const [number1, dispatch1] = useReducer(reducer, 1);
  const [number2, dispatch2] = useReducer(reducer, 2);
  return (
    <>
      <button
        onClick={() => {
          dispatch1({ type: 'add' });
          dispatch2({ type: 'add' });
        }}
      >
        +1
      </button>

      <p>{number1}</p>
      <p>{number2}</p>
    </>
  );
}
